#include "mystdio.h"
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>

MyFile *Myfopen(const char *filename, const char *mode)
{
  int flag = 0;
  if (strcmp(mode, "r") == 0)
  {
    flag |= O_RDONLY;
  }
  else if (strcmp(mode, "w") == 0)
  {
    flag |= O_WRONLY | O_CREAT | O_TRUNC;
  }
  else if (strcmp(mode, "a") == 0)
  {
    flag |= O_WRONLY | O_CREAT | O_APPEND;
  }
  else
  {
    return NULL;
  }
  int fd = 0;
  if (flag & O_RDONLY)
  {
    umask(0)
        fd = open(filename, flag, 0666);
  }
  else
  {
    fd = open(filename, flag);
  }
  if (fd < 0)
    return NULL;
  MyFile *fp = (MyFile *)malloc(sizeof(MyFile));
  if (fp == NULL)
    return -1;
  fp->fileno = fd;
  fp->pos = 0;
  fp->cap = SIZE;
  fp->flush_mode = LINE_FLUSH; // 设置为行刷新
}
const char *to_modestring(int flag)
{
  if (flag & NONE_FLUSH)
    return "NONE";
  else if (flag & FULL_FLUSH)
    return "FULL";
  else if (flag & LINE_FLUSH)
    return "LINE";
  else
    return "UNKOWN";
}
void Myfflush(MyFile *fp)
{
  if (fp->pos == 0)
    return;
  write(fp->fileno, fp->outbuffer, fp->pos); // 刷新写入
  fp->pos = 0;                               // buffer位置0
}
int My_fwrite(MyFile *fp, const char *s, int size)
{
  memcpy(fp->outbuffer + fp->pos, s, size);
  fp->pos += size;

  // 2. 判断，是否要刷新
  if ((fp->flush_mode & LINE_FLUSH) && fp->outbuffer[fp->pos - 1] == '\n')
  {
    Myfflush(fp);
  }
  else if ((fp->flush_mode & FULL_FLUSH) && fp->pos == fp->cap)
  {
    Myfflush(fp);
  }
  return size;
}

void Myfclose(MyFile *fp)
{
  Myfflush(fp);
  close(fp->fileno);
  free(fp);
}
